import axios from 'axios'

import { useAuthTool } from '@/utils/auth'

// create an axios instance
const instance = axios.create({
  baseURL: import.meta.env.VITE_APP_API_URL, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000, // request timeout
})

// request interceptor
instance.interceptors.request.use(
  (config) => {
    // do something before request is sent
    const { getAuthToken } = useAuthTool()
    const token = getAuthToken()
    if (token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = token
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log('request error:' + error) // for debug
    return Promise.reject(error)
  },
)
// response interceptor
instance.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  (response) => {
    const res = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (!res.success) {
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;

      // handleError(res.status.code, res.status.message)

      //
      // if (res.status.code === 'AUTH_NOT_LOGIN') {
      //   // to re-login
      //   MessageBox.confirm(
      //     '你已登出，请重新登录',
      //     '登出提示', {
      //       confirmButtonText: '重新登录',
      //       cancelButtonText: '取消',
      //       type: 'warning'
      //     }).then(() => {
      //     store.dispatch('user/resetToken').then(() => {
      //       location.reload()
      //     })
      //   })
      // } else {
      //   if (res.status.code === 'UNKNOWN_EXCEPTION') {
      //     Message({
      //       message: '系统出现异常，请联系管理员。',
      //       type: 'error',
      //       duration: 5 * 1000
      //     })
      //   } else {
      //     Message({
      //       message: res.status.message || 'Error',
      //       type: 'error',
      //       duration: 5 * 1000
      //     })
      //   }
      // }
      return Promise.reject(res.status)
    } else {
      return response
    }
  },
  (error) => {
    console.log('err:' + error) // for debug
    return Promise.reject(error)
  },
)

export default instance
